package ee.serge.client.content.cp;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import ee.serge.client.AlertBox;
import ee.serge.client.Move;
import ee.serge.client.content.LoansRequester;
import ee.serge.service.Service;
import ee.serge.shared.ContentPopup;
import ee.serge.shared.Feedback;
import ee.serge.shared.Loan;
import ee.serge.util.BTextBox;
import ee.serge.util.ClickLabel;
import ee.serge.util.FormPanel;
import ee.serge.util.SimpleCallback;
import ee.serge.util.bootstrap.BButton;
import ee.serge.util.bootstrap.BButtonBar;
import ee.serge.util.bootstrap.BTable;

public class LoanEditPopup extends ContentPopup {

   public static void show(String key) {
      Service.getControlPanelService().getLoan(key, new SimpleCallback<Loan>() {

         @Override
         public void success(Loan result) {
            PopupPanel instance = new LoanEditPopup(result);
            instance.center();
            instance.show();
         }
      });
   }
   
   public static void showAddNew() {
      PopupPanel instance = new LoanEditPopup();
      instance.center();
      instance.show();
   }
   
   private Loan loan;   
   private TabLayoutPanel tabPanel;
   private VerticalPanel panel;
   private BTextBox nameTextBox;
   private CheckBox activeCheckBox;
   private BTextBox linkTextBox;
   private BTextBox imageTextBox;
   private BTextBox screenshotTextBox;
   private TextArea commentTextArea;
   private BTextBox minLoanTextBox;
   private BTextBox maxLoanTextBox;
   private BTextBox aprTextBox;
   private BTextBox annualInterest;
   private BTextBox transferFeesTextBox;
   private BTextBox periodTextBox;
   
   /**
    * Edit
    */
   public LoanEditPopup(Loan loan) {
      super(false);
      this.loan = loan;

      VerticalPanel panel = new VerticalPanel();
      
      tabPanel = new TabLayoutPanel(2.5, Unit.EM);
      tabPanel.setAnimationDuration(500);
      tabPanel.add(getLoanPanel(true), "Loan");
      tabPanel.add(getFeedbackPanel(loan.getFeedbackList()), "Reviews (" + loan.getFeedbackList().size() + ")");
      tabPanel.setSize("550px", "550px");
      
      BButtonBar buttonPanel = new BButtonBar();
      buttonPanel.add(new BButton("Save", BButton.SUCCESS, new SaveHandler(loan)));
      buttonPanel.add(new BButton("Close", new CloseHandler()));
      
      panel.add(tabPanel);
      panel.add(buttonPanel);
      
      ScrollPanel scroll = new ScrollPanel(panel);
      setSize("auto", "auto");
      setWidget(scroll);
   }
   
   /**
    * Add new
    */
   public LoanEditPopup() {
      super(false);

      VerticalPanel panel = new VerticalPanel();
      
      tabPanel = new TabLayoutPanel(2.5, Unit.EM);
      tabPanel.setAnimationDuration(500);
      tabPanel.add(getLoanPanel(false), "Loan");
      activeCheckBox.setValue(true);
      tabPanel.setSize("550px", "550px");
      
      BButtonBar buttonPanel = new BButtonBar();
      buttonPanel.add(new BButton("Add", BButton.PRIMARY, new AddNewHandler()));
      buttonPanel.add(new BButton("Cancel", new CloseHandler()));
      
      panel.add(tabPanel);
      panel.add(buttonPanel);
      
      ScrollPanel scroll = new ScrollPanel(panel);
      setSize("auto", "auto");
      setWidget(scroll);
   }
   
   private VerticalPanel getLoanPanel(boolean isEdit) {
      FormPanel form = new FormPanel();
      
      form.add("Name", nameTextBox = new BTextBox());
      form.add("Active", activeCheckBox = new CheckBox());
      form.add("Link", linkTextBox = new BTextBox());
      form.add("Image", imageTextBox = new BTextBox());
      form.add("Screenshot", screenshotTextBox = new BTextBox());
      form.add("Comment", commentTextArea = new TextArea());
      form.add("Minimum loan", minLoanTextBox = new BTextBox());
      form.add("Maximum loan", maxLoanTextBox = new BTextBox());
      form.add("APR", aprTextBox = new BTextBox());
      form.add("Annual interest", annualInterest = new BTextBox());
      form.add("Transfer fee", transferFeesTextBox = new BTextBox());
      form.add("Period", periodTextBox = new BTextBox());
      
      if (isEdit) {
         form.add("Key", new Label(loan.getKey()));
         nameTextBox.setText(loan.getName());
         activeCheckBox.setValue(loan.isActive());
         linkTextBox.setText(loan.getLink());
         imageTextBox.setText(loan.getImageLink());
         annualInterest.setText(loan.getAnnualInterest());
         screenshotTextBox.setText(loan.getScreenshotLink());
         commentTextArea.setText(loan.getComment());
         minLoanTextBox.setText(loan.getMinLoan());
         maxLoanTextBox.setText(loan.getMaxLoan());
         aprTextBox.setText(loan.getAPR());
         periodTextBox.setText(loan.getPeriod());
         transferFeesTextBox.setText(loan.getTransferFee());
      }
      
      
      panel = new VerticalPanel();
      panel.add(form);
      return panel;
   }
   
   private Widget getFeedbackPanel(List<Feedback> feedbackList) {
      String[] headers = {"#", "Comment", "IP", ""};
      BTable table = new BTable(feedbackList.size(), headers, BTable.ZEBRA_STRIPED);
      for (int i = 0; i < feedbackList.size(); i++) {
         Feedback feedback = feedbackList.get(i);
         table.setText(i, 0, String.valueOf(i + 1) + ".");
         table.setText(i, 1, feedback.getComment());
         table.setWidget(i, 2, new ClickLabel(feedback.getIpAddress(), new IPAdressClickHandler(feedback.getIpAddress())));
         table.setWidget(i, 3, new ClickLabel("Remove", new RemoveFeedbackHandler(feedback.getKey())));
      }

      panel = new VerticalPanel();
      panel.add(table);
      return panel;
   }
   
   private Loan getLoan() {
      try {
         return new Loan(
               nameTextBox.getText(),
               linkTextBox.getText(), 
               commentTextArea.getText(), 
               Integer.valueOf(minLoanTextBox.getText()), 
               Integer.valueOf(maxLoanTextBox.getText()), 
               Integer.valueOf(aprTextBox.getText()),
               Integer.valueOf(annualInterest.getText()),
               Integer.valueOf(transferFeesTextBox.getText()),
               Integer.valueOf(periodTextBox.getText()), 
               activeCheckBox.getValue(),
               imageTextBox.getText(),
               screenshotTextBox.getText(),
               0,
               0,
               new ArrayList<Feedback>());
      } catch (Exception e) {
         AlertBox.showError("Invalid data");
      }
      return null;
   }
   
   private class SaveHandler implements ClickHandler {
      private Loan oldLoan;
      public SaveHandler(Loan oldLoan) {
         this.oldLoan = oldLoan;
      }
      @Override
      public void onClick(ClickEvent event) {
         Loan loan = getLoan();
         loan.setFeedbackList(this.oldLoan.getFeedbackList());
         loan.setKey(oldLoan.getKey());
         loan.setId(oldLoan.getId());
         loan.setCreationTime(oldLoan.getCreationTime());
         Service.getControlPanelService().saveLoan(loan, new SimpleCallback<Void>() {

            @Override
            public void success(Void result) {
               Move.get().goToContent(LoansPanelContent.getURLData());
               AlertBox.showSuccess("Loan saved");
               if (LoansRequester.isInitialised()) LoansRequester.get().refresh();
               hide();
            }
         });
      }
      
   }
   
   private class AddNewHandler implements ClickHandler {

      @Override
      public void onClick(ClickEvent event) {
         Service.getControlPanelService().addLoan(getLoan(), new SimpleCallback<Void>() {

            @Override
            public void success(Void result) {
               Move.get().goToURLData(LoansPanelContent.getURLData());
               AlertBox.showSuccess("Loan added");
               hide();
            }
         });
      }
      
   }
   
   private class CloseHandler implements ClickHandler {

      @Override
      public void onClick(ClickEvent event) {
         LoanEditPopup.this.hide();
      }
      
   }

   private class IPAdressClickHandler implements ClickHandler {
      private final String ip;
      public IPAdressClickHandler(String ip) {
         this.ip = ip;
      }
      @Override
      public void onClick(ClickEvent event) {
         Move.get().goToURLData(IPContent.getURLData(ip));
         LoanEditPopup.this.hide();
      }
      
   }
   
   private class RemoveFeedbackHandler implements ClickHandler {
      private String key;
      public RemoveFeedbackHandler(String key) {
         this.key = key;
      }
      @Override
      public void onClick(ClickEvent event) {
         Service.getControlPanelService().removeFeedback(key, new SimpleCallback<Void>() {

            @Override
            public void success(Void result) {
               AlertBox.showSuccess("Review removed");
            }
         });
      }
   }
   
}
